package cn.itsource.service.impl;

import cn.hutool.core.date.DateTime;
import cn.itsource.api.LoginRemoteApi;
import cn.itsource.constants.ErrorCode;
import cn.itsource.pojo.domain.Customer;
import cn.itsource.mapper.CustomerMapper;
import cn.itsource.pojo.domain.Login;
import cn.itsource.result.JSONResult;
import cn.itsource.service.ICustomerService;
import cn.itsource.utils.BitStatesUtils;
import cn.itsource.utils.IdUtils;
import cn.itsource.utils.NameUtil;
import cn.itsource.wechatTemplate.WechatLoginTemplate;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 客户 服务实现类
 * </p>
 *
 * @author yh
 * @since 2024-09-05
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements ICustomerService {

    @Autowired
    private WechatLoginTemplate wechatLoginTemplate;

    @Autowired
    private LoginRemoteApi loginRemoteApi;

    @Autowired
    private CustomerMapper customerMapper;


    @Override
    public JSONResult wechatRegister(String code) {
        String openId = wechatLoginTemplate.OpenId(code);
        Customer customer1 = customerMapper.selectOne(new LambdaQueryWrapper<Customer>().eq(Customer::getOpenId, openId));
        if(customer1==null){
            Customer customer = new Customer();

            customer.setId(IdUtils.getId());
            customer.setSex(1);
            customer.setCreateTime(DateTime.now());
            customer.setOpenId(openId);
            customer.setPhone("123456");
            customer.setName(NameUtil.getName());
            customer.setBitState(BitStatesUtils.OP_PHONE);
            customer.setLevel("0");
            super.save(customer);
            loginRemoteApi.create(getLogin(customer,openId));
            return JSONResult.success();
        }
        return JSONResult.error(ErrorCode.PARAM_PHONE_EXIST);
    }
    private static Login getLogin(Customer customer,String openId) {
        Login login =new Login();
        login.setId(IdUtils.getId());
        login.setUsername(customer.getName());
        login.setPassword("123456");
        login.setType(2);
        login.setNickName(customer.getName());
        login.setOpenId(openId);
        login.setName(customer.getName());
        login.setCreateTime(DateTime.now());
        return login;
    }
}
